﻿
namespace Numbrella.Tracker.Data
{
    using System;
    using System.Collections.ObjectModel;
    using System.Linq;

    public class ProblemsQueries
    {
        private readonly DatabaseEntities entities;

        public ProblemsQueries(DatabaseEntities entities)
        {
            this.entities = entities;
        }

        public ReadOnlyCollection<Problem> Get()
        {
            return (from p in entities.Problems select p).ToList().AsReadOnly();
        }

        public ReadOnlyCollection<Problem> GetActive(TimeSpan timeout)
        {
            DateTime aliveLimit = DateTime.Now - timeout;
            var problemsQuery = from p in this.entities.Problems
                                where p.Uri != null && p.LastNotify >= aliveLimit
                                select p;
            return problemsQuery.ToList().AsReadOnly();
        }

        public Problem Get(string userName, string problemName)
        {
            var problemQuery = from p in this.entities.Problems 
                               where p.Name == problemName && p.Owner.Name == userName 
                               select p;
            return (problemQuery.Count() == 0) ? null : problemQuery.First();
        }

        public Problem Get(User user, string problemName)
        {
            return this.Get(user.Name, problemName);
        }
    }
}